let Observer = (function() {
    let _messages = {};
    return {
        regist(type, fn) {
            if(typeof _messages[type] === 'undefined') {
                _messages[type] = [fn];
            }else{
                _messages[type].push(fn);
            }
        },
        fire(type, args) {
            if(!_messages[type])
                return;

            let events = {
                type: type,
                args: args || {}
            };
            for (let i = 0; i < _messages[type].length; i++) {
                _messages[type][i].call(this, events);
            }
        },
        remove(type, fn) {
            if(_messages[type] instanceof Array) {
                for(let i = _messages[type].length-1; i >= 0; i--) {
                    _messages[type][i] === fn && _messages[type].splice(i, 1);
                }
            }
        }
    }
})();

let Student = function (result) {
    this.result = result;
    let that = this;
    this.say = function() {
        console.log(that.result);
    }
};
Student.prototype.answer = function (question) {
    Observer.regist(question, this.say);
};
Student.prototype.sleep = function (question) {
    console.log(this.result + ' ' + question + ' 已被注销');
    Observer.remove(question, this.say);
};

let Teacher = function () {};
Teacher.prototype.ask = function (question) {
    console.log('问题是' + question);
    Observer.fire(question);
};

let student1 = new Student('学生1回答问题');
let student2 = new Student('学生2回答问题');
let student3 = new Student('学生3回答问题');

student1.answer('什么是设计模式');
student1.answer('简述观察者模式');
student2.answer('什么是设计模式');
student3.answer('什么是设计模式');
student3.answer('简述观察者模式');

student3.sleep('简述观察者模式');

let teacher = new Teacher();
teacher.ask('什么是设计模式');
teacher.ask('简述观察者模式');